package com.yuniot.todoapp

import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import org.eclipse.paho.android.service.MqttAndroidClient
import org.eclipse.paho.client.mqttv3.*
import java.lang.Exception

class MainActivity : AppCompatActivity() {
    // UI 组件
    private lateinit var statusText: TextView
    private lateinit var statusText1: TextView
    private lateinit var connectButton: Button
    private lateinit var disconnectButton: Button

    private lateinit var mqttClient: MqttAndroidClient

    // MQTT 连接参数
    private val serverUri =  "tcp://broker.hivemq.com:1883" // 公共测试服务器
    private val clientId = "Android_${System.currentTimeMillis()}"

    // 写死的订阅和发布主题
    private val subscribeTopic = "yuniot/sub" // 订阅主题
    private val publishTopic = "yuniot/pub"   // 发布主题

    //初始化事件
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        statusText = findViewById(R.id.statusText)
        statusText1 = findViewById(R.id.statusText1)

        connectButton = findViewById(R.id.connectButton)
        disconnectButton = findViewById(R.id.disconnectButton)

        //绑定连接按钮事件
        connectButton.setOnClickListener {
            connectToMqttBroker()
        }

        //绑定断开按钮事件
        disconnectButton.setOnClickListener {
            disconnectFromMqttBroker()
        }

        // 初始化 MQTT 客户端
        mqttClient = MqttAndroidClient(this, serverUri, clientId).apply {
            setCallback(object : MqttCallback {
                override fun messageArrived(topic: String?, message: MqttMessage?) {
                    // 当收到消息时调用
                    runOnUiThread {
                        val msg = "收到消息 [${topic}]: ${String(message?.payload ?: ByteArray(0))}"
                        statusText1.text = msg
                        Log.i("MQTT", msg)
                    }
                }

                override fun connectionLost(cause: Throwable?) {
                    runOnUiThread {
                        statusText.text = "连接丢失: ${cause?.message}"
                        Log.w("MQTT", "连接丢失: ${cause?.message}")
                    }
                }

                override fun deliveryComplete(token: IMqttDeliveryToken?) {
                    // 消息发布完成时调用
                    runOnUiThread {
                        statusText.text = "消息发布成功"
                        Log.i("MQTT", "消息发布成功")
                    }
                }
            })
        }
    }

    //弹出提示框
    private fun showErrorDialog(message: String) {
        AlertDialog.Builder(this)
            .setTitle("输入错误")
            .setMessage(message)
            .setIcon(android.R.drawable.ic_dialog_alert)
            .setPositiveButton("确定") { dialog, _ ->
                dialog.dismiss()
            }
            .show()
    }

    //连接MQTT
    private fun connectToMqttBroker() {
        try {
            val options = MqttConnectOptions().apply {
                isCleanSession = true
                connectionTimeout = 5
                keepAliveInterval = 60
            }

            runOnUiThread {
                statusText.text = "正在连接MQTT服务器..."
            }

            mqttClient.connect(options, null, object : IMqttActionListener {
                override fun onSuccess(asyncActionToken: IMqttToken?) {
                    runOnUiThread {
                        statusText.text = "已成功连接到MQTT服务器"
                        Log.i("MQTT", "✅ 连接成功! | ClientID: $clientId")

                        // 连接成功后订阅主题
                        subscribeToTopic()
                    }
                }

                override fun onFailure(asyncActionToken: IMqttToken?, exception: Throwable?) {
                    runOnUiThread {
                        statusText.text = "连接失败: ${exception?.message}"
                        Log.e("MQTT", "❌ 连接失败: ${exception?.message}")
                    }
                }
            })
        } catch (e: MqttException) {
            runOnUiThread {
                statusText.text = "MQTT异常: ${e.message}"
                Log.e("MQTT", "MQTT异常: ${e.message}")
            }
        }
    }

    // 订阅主题
    private fun subscribeToTopic() {
        try {
            if (!mqttClient.isConnected) {
                runOnUiThread {
                    statusText.text = "未连接服务器，无法订阅"
                    Log.w("MQTT", "未连接服务器，无法订阅")
                }
                return
            }

            // 订阅主题
            mqttClient.subscribe(subscribeTopic, 1, null, object : IMqttActionListener {
                override fun onSuccess(asyncActionToken: IMqttToken?) {
                    runOnUiThread {
                        statusText.text = "已成功订阅主题: $subscribeTopic"
                        Log.i("MQTT", "✅ 订阅成功: $subscribeTopic")

                        // 订阅成功后发布消息
                        publishMessage()
                    }
                }

                override fun onFailure(asyncActionToken: IMqttToken?, exception: Throwable?) {
                    runOnUiThread {
                        statusText.text = "订阅失败: ${exception?.message}"
                        Log.e("MQTT", "❌ 订阅失败: ${exception?.message}")
                    }
                }
            })
        } catch (e: Exception) {
            runOnUiThread {
                statusText.text = "订阅异常: ${e.message}"
                Log.e("MQTT", "订阅异常: ${e.message}")
            }
        }
    }

    // 发布消息
    private fun publishMessage() {
        try {
            if (!mqttClient.isConnected) {
                runOnUiThread {
                    statusText.text = "未连接服务器，无法发布"
                    Log.w("MQTT", "未连接服务器，无法发布")
                }
                return
            }

            // 创建消息
            val message = "Hello from Android Client"
            val mqttMessage = MqttMessage(message.toByteArray()).apply {
                qos = 1  // 服务质量等级 1
                //retained = false  // 不保留消息
            }

            // 发布消息
            mqttClient.publish(publishTopic, mqttMessage, null, object : IMqttActionListener {
                override fun onSuccess(asyncActionToken: IMqttToken?) {
                    runOnUiThread {
                        statusText.text = "已发布消息到 $publishTopic: $message"
                        Log.i("MQTT", "✅ 发布成功: $publishTopic - $message")
                    }
                }

                override fun onFailure(asyncActionToken: IMqttToken?, exception: Throwable?) {
                    runOnUiThread {
                        statusText.text = "发布失败: ${exception?.message}"
                        Log.e("MQTT", "❌ 发布失败: ${exception?.message}")
                    }
                }
            })
        } catch (e: Exception) {
            runOnUiThread {
                statusText.text = "发布异常: ${e.message}"
                Log.e("MQTT", "发布异常: ${e.message}")
            }
        }
    }

    //断开MQTT
    private fun disconnectFromMqttBroker() {
        try {
            if (!::mqttClient.isInitialized || !mqttClient.isConnected) return

            runOnUiThread {
                statusText.text = "正在断开连接..."
            }

            mqttClient.disconnect(null, object : IMqttActionListener {
                override fun onSuccess(asyncActionToken: IMqttToken?) {
                    runOnUiThread {
                        statusText.text = "已断开MQTT连接"
                        Log.i("MQTT", "已断开连接")
                    }

                    // 释放资源
                    mqttClient.unregisterResources()
                    mqttClient.close()
                }

                override fun onFailure(asyncActionToken: IMqttToken?, exception: Throwable?) {
                    runOnUiThread {
                        statusText.text = "断开连接失败: ${exception?.message}"
                        Log.e("MQTT", "断开连接失败: ${exception?.message}")
                    }
                }
            })
        } catch (e: MqttException) {
            runOnUiThread {
                statusText.text = "断开连接异常: ${e.message}"
                Log.e("MQTT", "断开连接异常: ${e.message}")
            }
        }
    }

    //关闭事件
    override fun onDestroy() {
        super.onDestroy()
        try {
            if (::mqttClient.isInitialized && mqttClient.isConnected) {
                disconnectFromMqttBroker()
            }
        } catch (e: Exception) {
            Log.e("MQTT", "onDestroy 异常: ${e.message}")
        }
    }
}